package com.ruoyi.iot.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.iot.domain.Device;
import com.ruoyi.iot.domain.DeviceAcl;
import com.ruoyi.iot.service.IDeviceAclService;
import com.ruoyi.iot.service.IDeviceService;
import com.ruoyi.iot.service.IProductService;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class IDeviceAclServiceImpl implements IDeviceAclService {

    @Resource
    private IProductService productService;

    @Resource
    private IDeviceService deviceService;
    
    @Override
    public DeviceAcl auth(DeviceAcl deviceAcl) {
        log.info("mqtt客户端请求连接:{}", JSON.toJSONString(deviceAcl));
        
        if(StringUtils.isBlank(deviceAcl.getUsername())||StringUtils.isBlank(deviceAcl.getPassword())||StringUtils.isBlank(deviceAcl.getClientid())) {
            deviceAcl.setResult("deny");
        }

        //根据自己业务需求增加逻辑，比如允许某公司三方设备连接，就过滤一下
        if(deviceAcl.getUsername().equals("holley")){
            deviceAcl.setResult("allow");
        }
        
        String[] usernameStr = deviceAcl.getUsername().split("&");
        if(usernameStr!=null && usernameStr.length != 2){
            deviceAcl.setResult("deny");
        }

        // 校验设备表，账号密码是否在，不存在不让连接
        Device device = deviceService.selectDeviceBySecret(usernameStr[0],deviceAcl.getPassword());
        if(device==null){
            deviceAcl.setResult("deny");
        }

        return deviceAcl;
    }

    @Override
    public DeviceAcl acl(DeviceAcl deviceAcl) {
        log.info("mqtt客户端请求订阅:{}", JSON.toJSONString(deviceAcl));
        if(deviceAcl.getClientid().startsWith("register-")&&deviceAcl.getTopic().startsWith("/ext/register/")){
            deviceAcl.setResult("allow");
        }

        //根据自己业务需求增加逻辑，比如允许某公司三方设备连接，就过滤一下
        if(deviceAcl.getUsername().contains("&")){ //设备连接使用
            deviceAcl.setResult("allow");
            return deviceAcl;
        }

        // 除了系统，不允许其他设备订阅通配符，否则有漏洞，设备之间不通过服务器可以收发其他设备指令
        if(deviceAcl.getTopic().contains("#")&&!deviceAcl.getTopic().startsWith("+")&&!deviceAcl.getUsername().contains("iot-transform")) {
            deviceAcl.setResult("deny");
            return deviceAcl;
        }

        return deviceAcl;
    }
    
}
